package com.example.yls.howold;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import javax.security.auth.login.LoginException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int MSG_SUCCESS = 101;
    private Button mGetImage;
    private Button mDetect;
    private TextView mTip;
    private ImageView mImageView;
    private View mWaiting;
    private String mCurrentPhotoStr;
    private static final int PICK_CODE =1001;
    private Bitmap mPhotoImg;
    private Handler mHandler;
    private Paint mPaint;
    private float top;//top：矩形框左上角像素点的纵坐标
    private float left;//left：矩形框左上角像素点的横坐标
    private float width;//width：矩形框的宽度
    private float heigth; //height：矩形框的高度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initEvents();
        initHandle();
        mPaint = new Paint();
    }

    private void initHandle() {
        mHandler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case MSG_SUCCESS:
                        mWaiting.setVisibility(View.GONE);
                        JSONObject jsonObject = (JSONObject) msg.obj;
                        prepareRsBitmap(jsonObject);
                        mImageView.setImageBitmap(mPhotoImg);
                        return true;
                }
                return false;
            }
        });
    }

    private void prepareRsBitmap(JSONObject jsonObject) {
        Bitmap bitmap = Bitmap.createBitmap(mPhotoImg.getWidth(),mPhotoImg.getHeight(),mPhotoImg.getConfig());
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(mPhotoImg,0,0,null);
        Gson gson = new Gson();
        String jsonStr = jsonObject.toString();
        Log.e("Gson", jsonStr);
        if(!jsonStr.equals("{\"error_message\":\"CONCURRENCY_LIMIT_EXCEEDED\"}")){
            Data data = gson.fromJson(jsonStr,Data.class);
            List<Data.FacesBean> faces = data.getFaces();
        mTip.setText("发现到"+faces.size()+"人");
        for (int i = 0; i <faces.size(); i++) {
            Data.FacesBean.FaceRectangleBean faceRectangleBean = faces.get(i).getFace_rectangle();
                top = faceRectangleBean.getTop();
                left = faceRectangleBean.getLeft();
                width = faceRectangleBean.getWidth();
                heigth = faceRectangleBean.getHeight();

            mPaint.setColor(0xffffffff);
            mPaint.setStrokeWidth(3);
            //画box
                canvas.drawLine(left,top,left+width,top,mPaint);
                canvas.drawLine(left,top,left,top+heigth,mPaint);
                canvas.drawLine(left+width,top,left+width,top+heigth,mPaint);
                canvas.drawLine(left,top+heigth,left+width,top+heigth,mPaint);

                 Data.FacesBean.AttributesBean attributes = faces.get(i).getAttributes();
                 try {
                     int age = attributes.getAge().getValue();
                     String gender = attributes.getGender().getValue();
                     Bitmap ageBitmap = buildAgeBitmap(age, "Male".equals(gender));
                     int ageWidth = ageBitmap.getWidth();
                     int ageHeight = ageBitmap.getHeight();


                     if (bitmap.getWidth() < mImageView.getWidth() && bitmap.getHeight() < mImageView.getHeight()) {
                         float ratio = Math.max(bitmap.getWidth() * 1.0f / mImageView.getWidth(),
                                 bitmap.getHeight() * 1.0f / mImageView.getHeight());
                         ageBitmap = Bitmap.createScaledBitmap(ageBitmap, (int) (ageWidth * ratio), (int) (ageHeight * ratio), false);
                     }
                     canvas.drawBitmap(ageBitmap, left-ageBitmap.getWidth()/4 , top - ageBitmap.getHeight(), null);
                     mPhotoImg = bitmap;
                 }catch (NullPointerException e){
                     Toast.makeText(MainActivity.this,"人群中混入了不男不女",Toast.LENGTH_SHORT).show();
                 }
            }
        }else {
            Toast.makeText(MainActivity.this,"请再点击",Toast.LENGTH_SHORT).show();
        }
//
    }

    private Bitmap buildAgeBitmap(int age, boolean isMale) {
        TextView textView = findViewById(R.id.id_age_and_gender);
        textView.setText(age+"");
        if(isMale){
            textView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.male),null,null,null);
        }else {
            textView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.female),null,null,null);
        }
        textView.setDrawingCacheEnabled(true);
        Log.e("textView", textView.toString());
        textView.measure(View.MeasureSpec.makeMeasureSpec(256,View.MeasureSpec.AT_MOST),
                View.MeasureSpec.makeMeasureSpec(256,View.MeasureSpec.AT_MOST));
//        //这个方法也非常重要，设置布局的尺寸和位置
        textView.layout(0,0,textView.getMeasuredWidth(), textView.getMeasuredHeight());
        textView.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(textView.getDrawingCache());
        textView.destroyDrawingCache();
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(requestCode==PICK_CODE){
            if(intent!=null){
                Uri uri = intent.getData();
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                cursor.moveToFirst();

                int dex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                mCurrentPhotoStr=cursor.getString(dex);
                cursor.close();
                resizePhoto();
                mImageView.setImageBitmap(mPhotoImg);
                mTip.setText("请点击识别 ==>");
            }
        }
        super.onActivityResult(requestCode,resultCode,intent);
    }

    private void resizePhoto() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeFile(mCurrentPhotoStr,options);

        double ratio = Math.max(options.outWidth*1.0d/1024f,options.outHeight*1.0d/1024f);
        options.inSampleSize= (int) Math.ceil(ratio);
        options.inJustDecodeBounds=false;
        mPhotoImg = BitmapFactory.decodeFile(mCurrentPhotoStr, options);
    }

    private void initEvents() {
        mGetImage.setOnClickListener(this);
        mDetect.setOnClickListener(this);
    }

    private void initViews() {
        mGetImage = findViewById(R.id.get_image);
        mDetect = findViewById(R.id.detect);
        mImageView = findViewById(R.id.image_view);
        mTip = findViewById(R.id.tip);
        mWaiting = findViewById(R.id.waiting);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.get_image:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,PICK_CODE);
                break;
            case R.id.detect:
                mWaiting.setVisibility(View.VISIBLE);
                if(mCurrentPhotoStr != null && !mCurrentPhotoStr.trim().equals("")){
                    resizePhoto();
                }else {
                    mPhotoImg = BitmapFactory.decodeResource(getResources(),R.drawable.t4);
                }
                FaceppDetect.detect(mPhotoImg, new FaceppDetect.CallBack() {
                    @Override
                    public void success(JSONObject result) {
                        Message message = new Message();
                        message.what=MSG_SUCCESS;
                        message.obj=result;
                        mHandler.sendMessage(message);
                    }
                });
                break;
        }
    }
}
